import GoogleMobileAds

public class RFAdmob: NSObject {
    
    public static let shared = RFAdmob()
    
    /**
     开屏广告
     */
    var appOpenAd: AppOpenAd?  //开屏广告对象
    
    public var isLoadingAd = false   //是否正在加载广告
    public var isShowingAd = false     //是否正在显示广告，此时开屏页显示在页面中
    public private(set) var loadCount: Int = 0       //app生命周期内，加载广告的次数, 只要发起了load就算一次
    public private(set) var loadedCount: Int = 0       //app生命周期内，加载广告成功的次数
    public private(set) var showCount: Int = 0       //app生命周期内，显示过广告的次数
    let timeoutInterval: TimeInterval = 4 * 3_600  //广告超时时间4小时
    public var loadTime: Date?     //加载广告完成时的时间，此时调用tryToPresentOpenAd可以正常跳转到广告页
    public var openAdId: String = "ca-app-pub-3940256099942544/5575463023"    //开屏广告App id, 默认不传使用测试id
    public var isDismissReloadAd = false       //dismiss广告时是否重新load广告，需要预加载考虑时可以置true, 比如后台到前台每次更新广告内容
    

    //是否已预加载广告成功
    public var isLoaded: Bool {
        return appOpenAd != nil
    }
    
    private override init(){}
    
    /// 初始化广告
    /// - Parameter callback: 可选。 回调结果是否准备完毕
    public func install(_ callback: ((Bool)->Void)? = nil){
#if DEBUG
        MobileAds.shared.requestConfiguration.testDeviceIdentifiers = [ "85c8e1dc0f1a2853e3480932229224b6" ]
#endif
        MobileAds.shared.start { status in
            let array = status.adapterStatusesByClassName.values
            if !array.isEmpty{
                if let cb = callback{
                    let item = array.first
                    
                    cb((item?.state.rawValue ?? 0) == 1)
                }
               
            }else{
                if let cb = callback{
                    cb(false)
                }
            }
//            print("【RFAdmob】广告初始化结果\(array)")
        }
        
        showCount = 0
        loadCount = 0
        loadedCount = 0
    }
}
//MARK: - 开屏广告
extension RFAdmob {
    /**
     unitId 对应的开屏广告id, 不默认使用测试账号
     
    hardLoad: 是否硬更新
     返回错误结果，nil表示成功
     */
    public  func requestAppOpenAd(hardLoad: Bool = false,_ callback: ((NSError?)->Void)? = nil) {
        if openAdId.isEmpty {
            #if DEBUG
            print("开屏广告unitId为空，预加载失败，直接返回")
            #endif
            if let cb = callback {
                cb(NSError(domain: "开屏广告unitId为空，预加载失败，直接返回", code: 1000))
            }
            return
        }
        let b = !hardLoad && (isLoadingAd || isAdAvailable() )
        if b { //已加载过广告，广告在有效期
            if let cb = callback {
                cb(nil)
            }
            return
        }
        isLoadingAd = true
        loadCount += 1
        AppOpenAd.load(with: openAdId, request: Request()) { openAd , err in
            self.isLoadingAd = false
            if let err = err {
                self.appOpenAd = nil
                self.loadTime = nil
                if let cb = callback {
                    cb(err as NSError?)
                }
                RFAdmobUtils.postSplashLoadeErrNotif(err as NSError)
            }else{
                self.loadedCount += 1

                self.appOpenAd = openAd
                self.loadTime = Date()
                self.appOpenAd?.fullScreenContentDelegate = self
                if let cb = callback {
                    cb(nil)
                }
                RFAdmobUtils.postSplashLoadedNotif()
            }
//            print("【RFAdmob】开屏广告初始化结果\(String(describing: err))")
            /*
             //报错说明:https://support.google.com/admob/thread/3494603?hl=en
             
             "Frequency cap reached. <https://support.google.com/admob/answer/9905175#6>" UserInfo={NSLocalizedDescription=Frequency cap reached. <https://support.google.com/admob/answer/9905175#6>, gad_response_info=  ** Response Info **
                 Response ID: (null)
                 Network: (null)

               ** Loaded Adapter Response **
                 (null)

               ** Extras Dictionary **
                 {
                 }

               ** Mediation line items **
             */
        }
    }
    
    /// 进入开屏广告页
    /// - Parameter vc: 当前页
    /// - Note 当调用requestAppOpenAd获取到正确结果后才会进行正常跳转，如未获取到，内部会自动调用requestAppOpenAd
    public func tryToPresentOpenAd(_ vc: UIViewController){
        if isShowingAd {  //App广告正在显示

            return
        }
        if !isAdAvailable() {
            requestAppOpenAd()
            return
        }
        if let openAd = appOpenAd {
            isShowingAd = true
            openAd.present(from: vc)
        }
    }
 //MARK: - 开屏私有方法
    public func isAdAvailable() -> Bool {
      // Check if ad exists and can be shown.
      return appOpenAd != nil && wasLoadTimeLessThanNHoursAgo(timeoutInterval: timeoutInterval)
    }
    private func wasLoadTimeLessThanNHoursAgo(timeoutInterval: TimeInterval) -> Bool {
      // Check if ad was loaded more than n hours ago.
      if let loadTime = loadTime {
        return Date().timeIntervalSince(loadTime) < timeoutInterval
      }
      return false
    }
}
extension RFAdmob: FullScreenContentDelegate {
    public func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) {
        showCount += 1
        RFAdmobUtils.postSplashShowedNotif()
    }
    public func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
        appOpenAd = nil
        isShowingAd = false
        if isDismissReloadAd {
            requestAppOpenAd()  //
        }
        RFAdmobUtils.postSplashDismissNotif()

    }
    public func adWillDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
        RFAdmobUtils.postSplashWillDismissNotif()
    }
    public func ad(
      _ ad: FullScreenPresentingAd,
      didFailToPresentFullScreenContentWithError error: Error
    ) {
    
      appOpenAd = nil
      isShowingAd = false
//      print("App open ad failed to present with error: \(error.localizedDescription).")
        RFAdmobUtils.postSplashShowErrNotif(error as NSError)
//        requestAppOpenAd(_openAdId)   //广告加载错误不进行重新load f/2023-02-13
    }

}

